<?php
include 'db_helper.php';


function listPLots() {
		$dbQuery = sprintf("SELECT * FROM parking_lot");
		$result = getDBResultsArray($dbQuery);
		header("Content-type: application/json");
		echo json_encode($result);
	}

function addCount($id,$newcount) {
	$dbQuery = sprintf("UPDATE parking_lot SET user_enroute_counter='%s' WHERE id_pk='%s'",mysql_real_escape_string($newcount),mysql_real_escape_string($id));
	$result = getDBResultAffected($dbQuery);

	header("Content-type: application/json");
	echo json_encode($result);

}

function getLotInfo($id) {
	$dbQuery = sprintf("SELECT * FROM parking_lot WHERE id_pk = '%s'", mysql_real_escape_string($id));
	$result = getDBResultRecord($dbQuery);
	header("Content-type: application/json");
	echo json_encode($result);
}

function sortAvail() {
	$dbQuery = sprintf("SELECT *, max_size - cur_occupied AS spots_avail FROM parking_lot ORDER BY spots_avail DESC");
	$result = getDBResultsArray($dbQuery);
	header("Content-type: application/json");
	echo json_encode($result);
}

/**
 * Find the distance between two lat and long points
 */
function distance($lat1, $lon1, $lat2, $lon2, $unit) { 
  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344); 
    } else {
        return $miles;
      }
}

/**
 * Compare two entries based on distance
 */
function compareDistance($entry1, $entry2)
{
    if ($entry1["distance"] == $entry2["distance"]) {
        return 0;
    }
    return ($entry1["distance"] < $entry2["distance"]) ? -1 : 1;
}

/**
 * Sorting parking lots based on distance
 */
function sortDist($currLocation) {
	$parts = explode(",",$currLocation);
	$currLat = floatval($parts[0]);
	$currLong = floatval($parts[1]);
	$dbQuery = sprintf("SELECT * FROM parking_lot");
	$result = getDBResultsArray($dbQuery);
	$final = array();
	foreach ($result as $entry){
		$lat = floatval($entry["latitude"]);
		$long = floatval($entry["longitude"]);
		$mile = distance($lat,$long,$currLat,$currLong,"M");
		$entry["distance"]=mysql_real_escape_string($mile);
		array_push($final, $entry);
	}
	usort($final,"compareDistance");
	header("Content-type: application/json");
	echo json_encode($final);
}
?>
